package com.glodon.paas.job.agent.worker;

import java.util.Timer;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

final class WorkerTimeoutTask extends TimerTask {
    private int cancelTimeout = 60 * 1000;
	private static final Logger logger = LoggerFactory.getLogger(WorkerTimeoutTask.class);

    private final Worker worker;
    private String cmd;
    public WorkerTimeoutTask(Worker worker,String cmd) {
        this.worker = worker;
        this.cmd = cmd;
    }

    @Override
    public void run() {
        logger.info("cancel worker");
        try {
        	Timer timer = startKillWorkerTimer();
            worker.cancel();
            logger.info("cancel worker success");
        	timer.cancel();
        } catch (WorkerException e) {
            throw new RuntimeException(e);
        }
    }
    
    public void setCancelTimeout(int cancelTimeout) {
		this.cancelTimeout = cancelTimeout;
	}

	private Timer startKillWorkerTimer() {
		Timer timer = new Timer(true);
		KillWorkerTask killTask = new KillWorkerTask(Thread.currentThread(), cmd);
		timer.schedule(killTask, cancelTimeout);
		return timer;
	}
}
